package org.gongliang.jfinal.controller.sys;

import java.util.List;

import org.gongliang.jfinal.common.base.Result;
import org.gongliang.jfinal.controller.BaseController;
import org.gongliang.jfinal.model.Resources;
import org.gongliang.jfinal.model.Role;

import com.jfinal.aop.Before;
import com.jfinal.json.JFinalJson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.JsonRender;


public class RoleController extends BaseController<Role>{
	
	public void main() {
		render("/views/sys/Role/main.html");
	}

	public void resPage() {
		setAttr("roleId", getPara("roleId"));
		render("/views/sys/Role/res.html");
	}

	public void updatePage() {
		render("/views/sys/Role/role.html");
	}
	
	public void getUserRole(){
		Result result = Result.success("查询用户角色成功!");
		int userId=getParaToInt("userId");
		List<Role> roles=Role.dao.getUserRole(userId);
		result.setResData(roles);
		render(new JsonRender(result).forIE());
	}
	@Before(Tx.class)
	public void saveUserRole(){
		Result result = Result.success("保存用户角色成功!");
		int userId=getParaToInt("userId");
		Integer[] roleIds=getParaValuesToInt("roleIds[]");
		Db.update("delete from sys_user_role where user_id=?",userId);
		if (null != roleIds && roleIds.length > 0) {
			for (int roleId : roleIds) {
				Record record = new Record();
				record.set("user_id", userId);
				record.set("role_id", roleId);
				Db.save("sys_user_role", record);
			}
		}
		render(new JsonRender(result).forIE());
	}

	public void getRoleResources() {
		Result result = Result.success("查询角色资源成功!");
		int roleId = getParaToInt("roleId");
		List<Record> roles = Resources.dao.getRoleResources(roleId);
		result.setResData(roles);
		render(new JsonRender(JFinalJson.getJson().toJson(result)).forIE());
	}

	@Before(Tx.class)
	public void saveRoleResources() {
		Result result = Result.success("保存角色资源成功!");
		int roleId = getParaToInt("roleId");
		Integer[] resourcesIds = getParaValuesToInt("resourcesIds[]");
		Db.update("delete from sys_role_resources where role_id=?", roleId);
		if (resourcesIds != null && resourcesIds.length > 0) {
			for (int resourcesId : resourcesIds) {
				Record record = new Record();
				record.set("resources_id", resourcesId);
				record.set("role_id", roleId);
				Db.save("sys_role_resources", record);
			}
		}
		render(new JsonRender(result).forIE());
	}
	
	@Override
	public String getSql() {
    	String sql="select * from "+tablename;
		return sql;
	}

}
